package com.zzj.ecology.admin.controller.system;

import com.zzj.ecology.admin.controller.BaseController;
import com.zzj.ecology.common.constant.GlobalConstant;
import com.zzj.ecology.common.constant.UrlConstants;
import com.zzj.ecology.common.enums.BusinessType;
import com.zzj.ecology.common.utils.StringUtils;
import com.zzj.ecology.framework.annotation.Log;
import com.zzj.ecology.framework.annotation.RepeatSubmit;
import com.zzj.ecology.framework.configuration.security.CustomizeFilterInvocationSecurityMetadataSource;
import com.zzj.ecology.system.bean.system.SysRole;
import com.zzj.ecology.system.domain.Page;
import com.zzj.ecology.system.dto.HttpResult;
import com.zzj.ecology.system.service.system.SysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@Api(value = "SysRole", description = "SysRole系统角色操作相关接口")
public class SysRoleController extends BaseController {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private CustomizeFilterInvocationSecurityMetadataSource metadataSource;


    /**
     * 分页查询 角色 列表数据
     * @return
     */
    @ApiImplicitParam(name = "page", value = "分页Page对象", required = true, dataTypeClass = Page.class)
    @ApiOperation(value = "查询角色列表分页数据", notes = "查询角色列表分页数据", httpMethod = "GET")
    @RequestMapping(value = UrlConstants.RoleUrl.LIST)//"/ajax/admin/sysRole/list")
    public HttpResult findPageList(Page page) {
        HttpResult result = sysRoleService.findPageList(page);
        return success(result);
    }

    /**
     * 查询 用户-角色页面上的 lay_transfer 数据, 并查询当前用户所拥有的角色列表数据
     * @return
     */
    @ApiImplicitParam(name = "userId", value = "登录用户的ID", required = true, dataType = "Integer")
    @ApiOperation(value = "查询角色穿梭框数据", notes = "查询角色穿梭框数据及查询传入的用户ID的拥有的角色", httpMethod = "POST")
    @RequestMapping(value = UrlConstants.RoleUrl.FIND_TRANSFER_LIST)
    public HttpResult findTransferList(Integer userId) {
        HttpResult result = sysRoleService.findTransferList(userId);
        return success(result);
    }

    /**
     * 新角色创建, 创建角色基本信息,并赋予基本菜单功能
     * @param sysRole
     * @return
     */
    @ApiOperation(value = "角色创建", notes = "创建一个新的角色，注意：角色别名不可重复。", httpMethod = "POST")
    @RepeatSubmit
    @Log(title = "角色管理",businessType = BusinessType.INSERT)
    @PostMapping(value = UrlConstants.RoleUrl.CREATE)
    public HttpResult create(@ApiParam SysRole sysRole) {
        sysRole.setCreateAt(new Date());
        sysRole.setCreateBy(getUsername());
        sysRole.setDeleteStatus(GlobalConstant.DELETE_STATUS_NOT_DELETE);
        sysRoleService.createAndInitializeMenuAndBuildPermissionRelation(sysRole);
        return success();
    }

    @ApiOperation(value = "角色创建", notes = "查询角色别名是否已经存在。如果存在返回 true，已经存在返回 false", httpMethod = "GET")
    @RequestMapping(value = UrlConstants.RoleUrl.CHECK_ROLECODE_EXIST)
    public boolean checkRoleCodeExist(@RequestParam(value = "roleCode", required = true) @ApiParam String roleCode) {
        if(StringUtils.isEmpty(roleCode)) return false;
        boolean b = sysRoleService.checkRoleCodeExist(roleCode);
        return b;
    }


    /**
     * 角色删除, 标记 delete_status='0' 等于 '1'
     * @param roleids
     * @return
     */
    @ApiOperation(value = "角色删除", notes = "查询角色别名是否已经存在。如果存在返回 true，已经存在返回 false", httpMethod = "POST")
    @RepeatSubmit
    @Log(title = "角色管理",businessType = BusinessType.DELETE)
    @PostMapping(value = UrlConstants.RoleUrl.DELETE_BY_IDS)
    public HttpResult deleteByIds(@RequestParam(name = "ids", required = true) @ApiParam List<Integer> roleids) {
        if(roleids.size() <= 0) return error();
        HttpResult result = sysRoleService.updateDeleteStatusByIds(roleids, getUsername());
        return success(result);
    }

    /**
     * 修改角色基本信息,如果角色名称(角色代码不可修改),备注信息,系统自动获取到当前登录人员作为 修改人员和记录修改时间
     * @param sysRole
     * @return
     */
    @ApiOperation(value = "角色修改", notes = "根据 角色ID 修改 角色 信息", httpMethod = "POST")
    @RepeatSubmit
    @Log(title = "角色管理",businessType = BusinessType.UPDATE)
    @PostMapping(value = UrlConstants.RoleUrl.UPDATE)
    public HttpResult update(@ApiParam SysRole sysRole) {
        sysRole.setUpdateAt(new Date());
        sysRole.setUpdateBy(getUsername());
        HttpResult result = sysRoleService.update(sysRole);
        return success(result);
    }

    /**
     * 未设置 laytree 的 field 字段值时，默认FORM提交的是 layuiTreeCheck_各选中ID
     * @param roleId
     * @param laytreeids
     * @return
     */
    @ApiOperation(value = "分配菜单", notes = "给指定角色分配或重新分配相应的菜单，查询相对的菜单权限并把菜单对应的权限分配给用户", httpMethod = "POST")
    @RepeatSubmit
    @Log(title = "角色管理",businessType = BusinessType.GRANT)
    @PostMapping(value = UrlConstants.RoleUrl.REGRANT_MENUS)
    public HttpResult reGrantMenus(@RequestParam(name = "roleId", required = true)Integer roleId, @RequestParam(name = "ids") List<Integer> laytreeids) {
        System.out.println(laytreeids.size());
        HttpResult result = sysRoleService.reBuildRoleMenuRelation(new SysRole(roleId, new Date(), getUsername()), laytreeids);
        return success(result);
    }

    /**
     * 根据 角色ID 查询到当前 角色所拥有的 所有菜单(不管菜单 是否被标记为0)
     * @param roleId
     * @return
     */
    @ApiOperation(value = "查询角色的菜单", notes = "查询到指定角色所拥有的菜单", httpMethod = "GET")
    @RequestMapping(value = UrlConstants.RoleUrl.FIND_MENUS_BY_ROLEID)
    public HttpResult findMenusByRoleId(Integer roleId) {
        HttpResult result = sysRoleService.findMenusByRoleId(roleId);
        return success(result);
    }








//
//    /**
//     * 创建角色 并 授予权限
//     * @param sysRole
//     * @param permissionids
//     * @return
//     */
//    @PostMapping(value = "/admin/sysRole/ajax/createAndGrant")
//    public HttpResult createAndGrant(SysRole sysRole, Integer[] permissionids) {
//        HttpResult result = sysRoleService.createAndGrant(sysRole, permissionids);
//        //if(permissionids != null && permissionids.length >= 0) System.out.println(permissionids.length);
//        metadataSource.loadResourceDefine();//加载权限
//        return result;//HttpResult.success();
//    }
//
//
//    /**
//     * 修改角色 并 重新 授予权限
//     * @param sysRole
//     * @param permissionids
//     * @return
//     */
//    @PostMapping(value = "/admin/sysRole/ajax/updateAndGrant")
//    public HttpResult updateAndGrant(SysRole sysRole, Integer[] permissionids) {
//        HttpResult result = sysRoleService.updateAndPermissionGrant(sysRole, permissionids);
//        metadataSource.loadResourceDefine();//加载权限
//        return result;
//    }
//
//    @PostMapping(value = "/admin/sysRole/ajax/deleteAndGrantByIds")
//    public HttpResult deleteAndGrant(@RequestParam("ids") Integer[] ids) {
//        if (ids == null || ids.length == 0) {
//            return HttpResult.error();
//        }
//        HttpResult result = sysRoleService.deleteAndGrant(ids);
//        metadataSource.loadResourceDefine();//加载权限
//        return result;
//    }
//
//
//
//
//    /**
//     * 根据前端提供的 roleName 查询数据库是否存在，不存在返回 true
//     * @param roleName
//     * @return
//     */
//    @PostMapping(value = "/admin/sysRole/ajax/isNotExistRoleName")
//    public boolean isNotExistRoleName(String roleName) {
//        if (StringUtils.isEmpty(roleName)) {
//            return false;
//        }
//        boolean isNoExist = sysRoleService.isNotExistRoleName(roleName);
//        return isNoExist;
//    }
//
//    /**
//     * 根据前端提供的 roleCode 查询数据库是否存在，不存在返回 true
//     * @param roleCode
//     * @return
//     */
//    @PostMapping(value = "/admin/sysRole/ajax/isNotExistRoleCode")
//    public boolean isNotExistRoleCode(String roleCode) {
//        if (StringUtils.isEmpty(roleCode)) {
//            return false;
//        }
//        boolean isNoExist = sysRoleService.isNotExistRoleCode(roleCode);
//        return isNoExist;
//    }
//
//    /**
//     * 未设置 laytree 的 field 字段值时，默认FORM提交的是 layuiTreeCheck
//     * @param roleid
//     * @param layuiTreeCheck
//     * @return
//     */
//    @PostMapping(value = UrlConstants.ROLE_UPDATE_MENUGRANT)
//    public HttpResult updateAndMenuGrant(Integer roleid,Integer[] layuiTreeCheck) {
//        if(roleid == null || layuiTreeCheck == null || layuiTreeCheck.length < 0) return HttpResult.error();
//        HttpResult result = sysRoleService.updateAndMenuGrantByRoleId(roleid,layuiTreeCheck);
//        return result;
//    }
//
//    /**
//     * 查询所有角色，返回layui transfer 用数据，
//     * 返回 datalist1 全部数据
//     * 返回 datalist2 已经存在数据
//     * @param userid
//     * @return
//     */
//    @PostMapping(value = UrlConstants.ROLE_FIND_TRANSFER_LIST_BY_USERID)
//    public HttpResult findTransferListByUserId(Integer userid) {
//        HttpResult result = sysRoleService.findTransferListByUserId(userid);
//        return result;
//    }

}
